<?php

namespace app\common\logic\system;

use app\common\logic\BaseLogic;
use app\common\model\system\AdminModel;
use app\common\service\JsonService;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class AdminLogic extends BaseLogic
{
    /**
     * token加密的key
     * @var string
     */
    private $tokenKey = 'myadmin147258369';
    /**
     * token加密的算法
     * @var string
     */
    private $tokenAlg = 'HS256';
    /**
     * token有效期（秒数）
     * @var int
     */
    private $tokenExpire = 3600 * 24 * 7;


    /**
     * 生成token
     * @return string
     */
    public function buildToken($adminInfo): string
    {
        $payload = [
            'is_root' => $adminInfo['is_root'],
            'admin_id' => $adminInfo['id'],
            'username' => $adminInfo['username'],
            'sex' => $adminInfo['sex'],
            'mobile' => $adminInfo['mobile'],
            'email' => $adminInfo['email'],
            'avatar' => $adminInfo['avatar'],
            'name' => $adminInfo['name'],
            'expire_time' => time() + $this->tokenExpire
        ];

        return JWT::encode($payload, $this->tokenKey, $this->tokenAlg);
    }

    /**
     * 解析token
     * @return mixed
     */
    public function explainToken($token): array
    {
        return json_decode(json_encode(JWT::decode($token, new Key($this->tokenKey, $this->tokenAlg))), true);
    }

    /**
     * 验证access_token并返回身份信息
     * @param $token
     * @return mixed
     */
    public function checkToken($token): array
    {
        $payload = $this->explainToken($token);
        if ($payload['expire_time'] < time()) {
            abort(402, '身份认证已过期');
        }
        return $payload;
    }


    /**
     * 登录
     * @param array $data 登录数据
     * @param string $type 登录方式
     * @return string 返回token
     */
    public function login(array $data, string $type = 'account') : string{
        if($type == 'account'){
            return $this->loginByAccount($data['username'],$data['password']);
        }

        JsonService::throw('登录方式有误：'.$type);
    }

    /**
     * 账户密码登录
     * @param $username
     * @param $password
     * @return string
     */
    private function loginByAccount($username, $password): string{
        $admin = AdminModel::where('username',$username)->findOrEmpty();
        if($admin->isEmpty() ){
            JsonService::throw('账号或密码有误');
        }elseif($admin->status != 1){
            JsonService::throw('账号已被停用');
        }elseif($admin->password != $this->encryptPassword($password)){
            JsonService::throw('账号或密码有误');
        }

        return $this->buildToken($admin);
    }

    /**
     * 加密登录密码
     * @param string $password 登录密码原文
     * @param string $salt 加密盐
     * @return string
     */
    public function encryptPassword(string $password, string $salt = 'myadmin'): string
    {
        return md5(sha1($salt . sha1($password . $salt) . $salt) . $salt);
    }


}